package main

import (
	"fmt"
	"log"
	"time"

	"github.com/robinson/gos7"
)

func main() {
	// PLC 连接配置
	handler := gos7.NewTCPClientHandler("192.168.0.1", 0, 1)
	handler.Timeout = 5 * time.Second
	handler.IdleTimeout = 10 * time.Second

	// 连接到 PLC
	if err := handler.Connect(); err != nil {
		log.Fatalf("连接失败: %v", err)
	}
	defer handler.Close()

	client := gos7.NewClient(handler)

	// 数据请求列表，每个元素包含地址、起始位置、类型和读取大小
	dataRequests := []struct {
		Address string
		Start   int
		Type    int
		Size    int
	}{
		{"DB1", 3936, 6, 2}, // 读取 2 字节的 INT 类型
		{"DB1", 3940, 6, 2},
		{"DB1", 5001, 8, 1}, // 读取 1 字节的 BOOL 类型
		{"DB1", 5001, 8, 1},
		{"DB1", 5020, 6, 2},
		{"DB1", 5024, 2, 1}, // 读取 1 字节的 CHAR 类型
		{"DB1", 5200, 6, 2},
		{"DB1", 5270, 2, 1},
		{"DB1", 7200, 6, 2},
		{"DB1", 7300, 6, 2},
		{"DB1", 9210, 6, 2},
		{"DB1", 9218, 6, 2},
		{"DB1", 7, 8, 1}, // 读取 1 位的 BOOL 类型
		{"M", 5, 8, 1},  // M 区
		{"DB1", 11, 8, 1}, // 读取 1 位的 BOOL 类型
	}

	// 合并请求并执行批量读取
	readItems := make([]gos7.ReadItem, len(dataRequests))
	for i, req := range dataRequests {
		readItems[i] = gos7.ReadItem{
			Area:   gos7.AreaDB,  // DB 区
			DbNumber: 1,        // DB1
			Start:  req.Start,  // 起始地址
			Length: req.Size,   // 读取长度
		}
	}

	// 执行批量读取
	results, err := client.ReadMultiData(readItems)
	if err != nil {
		log.Fatalf("批量读取失败: %v", err)
	}

	// 输出读取结果
	for i, result := range results {
		if result.Error != nil {
			log.Printf("读取 %d 失败: %v", i, result.Error)
		} else {
			fmt.Printf("读取 %s 结果: %x\n", dataRequests[i].Address, result.Data)
		}
	}
}
